package com.where.test.sevice;

import com.aliyun.oss.OSSClient;
import com.where.test.config.OSSPropertiesConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: where
 * @Date: 2023/02/27/10:37
 * @Description: OSS 方法包装
 */
@Service
public class OssUtils {
    @Autowired
    private OSSPropertiesConfig ossConfig;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    public String upload(MultipartFile file) throws IOException {
        if (ObjectUtils.isEmpty(file)) {
            return "null";
        }
        // 1、OssClient初始化
        OSSClient ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getKeyId(), ossConfig.getKeySecret());
        // 2.文件名称
        String filename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid + filename;
        // 父文件夹
//        String date = DateUtils.getCurrentDate();
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/hh");
        String date = format.format(new Date());
        System.out.println(date);
        filename = date + "/" + filename;

        // 3.保存地址
        ossClient.putObject(ossConfig.getBucketName(), filename, file.getInputStream());

        System.out.println(file);

        // 返回url
        //https://xppll.oss-cn-beijing.aliyuncs.com/01.jpg
        String url = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + filename;
        //关闭OSSClient
        ossClient.shutdown();

        return url;
    }
}
